<template>
  <div class="wrap">
    <div id="chart1"></div>
  </div>
</template>
<script>
import { getChart1Data } from "@/api/first-loan.js";
import elementResizeDetectorMaker from "element-resize-detector";
import echarts from "echarts";
export default {
  name: "chart1",
  props: {
    actived: Boolean,
    chartName: String
  },
  data() {
    return {
      chart: null,
      category: [],
      legend: ["户数", "加权利率"],
      series1: [],
      series2: []
    };
  },
  methods: {
    drawChart() {
      this.chart.setOption({
        title: {
          text: this.chartName,
          left: "center",
          align: "right"
        },
        xAxis: {
          type: "category",
          data: this.category
        },
        yAxis: [
          {
            name: "户数(户)",
            type: "value"
          },
          {
            name: "加权利率(%)",
            type: "value"
          }
        ],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            animation: false,
            label: {
              backgroundColor: "#505765"
            }
          }
        },
        legend: {
          data: this.legend,
          left: 10
        },
        series: [
          {
            name: this.legend[0],
            data: this.series1,
            type: "bar",
            smooth: true
          },
          {
            name: this.legend[1],
            data: this.series2,
            type: "line",
            smooth: true,
            yAxisIndex: 1
          }
        ]
      });
    }
  },
  mounted() {
    const _this = this;
    let erd = elementResizeDetectorMaker(document.getElementsByClassName("wrap"), function(
      element
    ){
      let width = element.offsetWidth;
      let height = element.offsetHeight;
      _this.$nextTick(function(){
        this.drawChart();
      })
    });
  },
  watch: {
    actived() {
      if (!this.actived) {
        return;
      }
      getChart1Data({})
        .then(res => {
          res.forEach(item => {
            this.category.push(item.month);
            this.series1.push(item.amount);
            this.series2.push(item.rate);
          });
          this.chart = echarts.init(document.getElementById("chart1"));
          this.chart.resize();
          this.drawChart();
        })
        .catch(errMsg => this.$alert(errMsg.msg));
    }
  }
};
</script>
<style lang="stylus" scoped>
.wrap {
  padding-top: 5px;
  padding-left: 5px;

  #chart1 {
    width: 100%;
    height: 350px;
  }
}
</style>